using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Configuration;
using System.Diagnostics;
using System.Resources;
using System.Runtime;

using FarseerPhysics.DemoBaseXNA.Components;
using FarseerPhysics.DemoBaseXNA;
using FarseerPhysics.DemoBaseXNA.ScreenSystem;
using FarseerPhysics;
using FarseerPhysics.Dynamics;
using FarseerPhysics.Dynamics.Contacts;
using FarseerPhysics.Dynamics.Joints;
using FarseerPhysics.Factories;
using FarseerPhysics.Collision;
using FarseerPhysics.Collision.Shapes;
using FarseerPhysics.Controllers;
using FarseerPhysics.Common;
using FarseerPhysics.Common.ConvexHull;
using FarseerPhysics.Common.Decomposition;
using FarseerPhysics.Common.PolygonManipulation;

using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.GamerServices;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Net;
using Microsoft.Xna.Framework.Storage;
using Microsoft.Xna.Framework.Media;
using Microsoft.Xna.Framework.Design;

using ProjectMercury;
using ProjectMercury.Emitters;
using ProjectMercury.Modifiers;
using ProjectMercury.Renderers;

namespace SimpleSamplesXNA
{


    

    /// <summary>
    /// This is the main type for your game
    /// </summary>
    public class AGameCalledPainting : Game
    {
        private AudioEngine audioEngine;
        private WaveBank waveBank;
        private SoundBank soundBank;
        AudioCategory music;
        AudioCategory DefaultAudioCategory;

        private GraphicsDeviceManager _graphics;
        private Texture2D SpriteTextureBall;//ball texture
        private Texture2D SpriteTextureBackGround1;//canvas background
        private Texture2D SpriteTexturePaintBrush;//cursor
        private Texture2D SpriteTextureGameMenu;//texture for main menu
        private Texture2D[] SpriteTextureMenuEntry = new Texture2D[4];
        private Texture2D SpriteTextureLinePoint;
        private Texture2D SpriteTextureBarrel;
        private Texture2D SpriteTextureBarrelBacking;
        private Texture2D SpriteTextureWin;
        private Texture2D SpriteTextureLoose;
        Vector2 SpriteTextureBallOrigin;//origin of ball picture
        Vector2 SpritePaintBrushOrigin = new Vector2(0, 0);//where mouse cursor is drawn
        Vector2 SpriteGameMenuOrigin = new Vector2(0, 0);//origin for main menu
        Vector2[] SpriteMenuEntryOrigins = new Vector2[4];//origin for all four menu entries
        Vector2 GameTitleOrigin = new Vector2(0, 0);
        Vector2 barrelPosLev1;
        int[] menuEntryOffsets = {0,0,0,0};//offset for where menu items are drawn on the X axis only-this is used for animation

        SpriteBatch spriteBatch;
        LevelOne lev1;
        SpriteFont Font;
        SpriteFont Font2;

        ResolveTexture2D renderTargetTexture;//for pausing game

        //screen dimensions
        int screenH = 0;
        int screenW = 0;


        



        //input states-----------------
        KeyboardState oldKS = Keyboard.GetState();
        MouseState oldMS = Mouse.GetState();

        //game state------------
        int gameMenuItemSelected = -1;//default is no item selected, this is the curent menu entry selected
        
        

        

        //sprite scalar variables---------------
        float ballScalar = 1;//scale for the ball when drawn


        //video for background
        Video IntroBackGroundMovie;
        VideoBackGround movie;









        /* 
        First you have to create the 2 performance counters 
        using the System.Diagnostics.PerformanceCounter class. 
        */ 

        protected PerformanceCounter cpuCounter; 
        protected PerformanceCounter ramCounter;
        FrameRateCounter frameRateCounter;

        /* 
        Call this method every time you need to know 
        the current cpu usage. 
        */ 

        public string getCurrentCpuUsage(){ 
                   return  cpuCounter.NextValue()+"%"; 
        } 

        /* 
        Call this method every time you need to get 
        the amount of the available RAM in Mb 
        */ 
        public string getAvailableRAM(){ 
                    return ramCounter.NextValue()+"Mb"; 
        } 














        public AGameCalledPainting()
        {

            Window.Title = "A Game Called Painting";
            _graphics = new GraphicsDeviceManager(this);

            _graphics.SynchronizeWithVerticalRetrace = false;

            TargetElapsedTime = new TimeSpan(0, 0, 0, 0, 16);
            IsFixedTimeStep = true;

            Content.RootDirectory = "Content";

            

            //fullscreen
            _graphics.PreferredBackBufferWidth = GraphicsAdapter.DefaultAdapter.CurrentDisplayMode.Width;
            _graphics.PreferredBackBufferHeight = GraphicsAdapter.DefaultAdapter.CurrentDisplayMode.Height;
            _graphics.IsFullScreen = true;

            GloabalStates.shrinkFactor = (float)_graphics.PreferredBackBufferWidth / 1440.0f;

            IsMouseVisible = false;

            //Set window defaults. Parent game can override in constructor
            Window.AllowUserResizing = true;
            Window.ClientSizeChanged += Window_ClientSizeChanged;

            //new-up components and add to Game.Components
            ScreenManager = new ScreenManager(this);
            Components.Add(ScreenManager);

            frameRateCounter = new FrameRateCounter(ScreenManager);
            //frameRateCounter.DrawOrder = 101;
            //Components.Add(frameRateCounter);
            //frameRateCounter.Enabled = true;
            //frameRateCounter.Visible = true;



            //performance checks----------------------------------------------------------------------------------------
            //for nvidia cards must meet minimun requirenment
            if (GraphicsAdapter.DefaultAdapter.DeviceId < 1573 && GraphicsAdapter.DefaultAdapter.VendorId != 0x10DE)
            {
                this.Exit();
            }

            //need dual core or better
            if (System.Environment.ProcessorCount < 2)
            {
                this.Exit();
            }

            cpuCounter = new PerformanceCounter();

            cpuCounter.CategoryName = "Processor";
            cpuCounter.CounterName = "% Processor Time";
            cpuCounter.InstanceName = "_Total";

            ramCounter = new PerformanceCounter("Memory", "Available MBytes");

            //not enough memory
            if (ramCounter.NextValue() < 512f)
            {
                this.Exit();
            }

            GloabalStates.performanceData.MonitorPerformance = true;
            //---------------------------------------------------------------------------------------------------------------




            lev1 = new LevelOne(this);
            ScreenManager.MainMenuScreen.AddMainMenuItem(lev1.GetTitle(), lev1);
            ScreenManager.MainMenuScreen.AddMainMenuItem("Exit", null, true);


            ScreenManager.GoToMainMenu();




            

           
            
        }

        public ScreenManager ScreenManager { get; set; }





















        /// <summary>
        /// Allows the game to perform any initialization it needs to before starting to run.
        /// This is where it can query for any required services and load any non-graphic
        /// related content.  Calling base.Initialize will enumerate through any components
        /// and initialize them as well.
        /// </summary>
        protected override void Initialize()
        {
            audioEngine = new AudioEngine("Content\\Audio\\sound1.xgs");
            waveBank = new WaveBank(audioEngine, "Content\\Audio\\Wave Bank.xwb");
            soundBank = new SoundBank(audioEngine, "Content\\Audio\\Sound Bank.xsb");
            music = audioEngine.GetCategory("Music");
            DefaultAudioCategory = audioEngine.GetCategory("Default");


            screenH = ScreenManager.ScreenHeight / 2;
            screenW = ScreenManager.ScreenWidth / 2;

            barrelPosLev1 = new Vector2((int)(ScreenManager.ScreenWidth / 2.8), (int)(ScreenManager.ScreenHeight / 1.7));
            

            //exit if resolution is too low
            if(ScreenManager.ScreenWidth < 800 || ScreenManager.ScreenHeight < 600)
                this.Exit();

            GameTitleOrigin = new Vector2((float)(ScreenManager.ScreenWidth / 4), ScreenManager.ScreenHeight / 9);

            //calculate offset based on default dimensions 800X600
            int wAdder = (ScreenManager.ScreenWidth - 800) / 2;
            int hAdder = (ScreenManager.ScreenHeight - 600) / 2;

            SpriteGameMenuOrigin = new Vector2(wAdder,hAdder);//set menu to new offsets
            SpriteMenuEntryOrigins[0] = new Vector2(wAdder+48, hAdder+135);
            SpriteMenuEntryOrigins[1] = new Vector2(wAdder+65, hAdder+239);
            SpriteMenuEntryOrigins[2] = new Vector2(wAdder+81, hAdder+332);
            SpriteMenuEntryOrigins[3] = new Vector2(wAdder+95, hAdder+423);


            
            _graphics.ApplyChanges();
            base.Initialize();
        }















        public Texture2D loadTexture2d(string s)
        {
            return Content.Load<Texture2D>(s);
        }

        public Video loadVideo(string s)
        {
            return Content.Load<Video>(s);
        }

























        /// <summary>
        /// Loads Game Content At very beggining of game load.
        /// </summary>
        protected override void LoadContent()
        {
            //load video
            IntroBackGroundMovie = loadVideo("Video\\1");
            movie = new VideoBackGround(IntroBackGroundMovie, true);
            movie.rect = new Rectangle(ScreenManager.ScreenWidth / 2, ScreenManager.ScreenHeight / 4, ScreenManager.ScreenWidth / 3, ScreenManager.ScreenHeight / 3);
            movie.play();

            // Create a new SpriteBatch, which can be used to draw textures.
            spriteBatch = new SpriteBatch(GraphicsDevice);
            SpriteTextureBall = loadTexture2d("Pictures\\Bubble");
            SpriteTextureBackGround1 = loadTexture2d("Pictures\\Canvas");
            SpriteTextureGameMenu = loadTexture2d("Pictures\\m2");
            SpriteTextureLinePoint = loadTexture2d("Pictures\\linedot");
            SpriteTextureBarrel = loadTexture2d("Pictures\\barel");
            SpriteTextureBarrelBacking = loadTexture2d("Pictures\\barel2");
            SpriteTextureWin = loadTexture2d("Pictures\\Win");
            SpriteTextureLoose = loadTexture2d("Pictures\\Loose");

            //loads pause menu entries into memory
            for (int x = 0; x < SpriteTextureMenuEntry.Length;x++ )
                SpriteTextureMenuEntry[x] = loadTexture2d("Pictures\\m1");

            SpriteTextureBallOrigin = new Vector2(SpriteTextureBall.Width / 2f, SpriteTextureBall.Height / 2f);
            Font = Content.Load<SpriteFont>("SpriteFont1");
            Font2 = Content.Load<SpriteFont>("SpriteFont2");
            SpriteTexturePaintBrush = loadTexture2d("Pictures\\PaintBrush3");


            //render texture target for screen shots for pause effect
            renderTargetTexture = new ResolveTexture2D(
                GraphicsDevice,
                GraphicsDevice.PresentationParameters.BackBufferWidth,
                GraphicsDevice.PresentationParameters.BackBufferHeight, 1,
                GraphicsDevice.PresentationParameters.BackBufferFormat);

            //loads paint picker textures
            PaintPicker.textures[0] = loadTexture2d("Pictures\\paintPickerMenuBacking");
            PaintPicker.textures[1] = loadTexture2d("Pictures\\up");
            PaintPicker.textures[2] = loadTexture2d("Pictures\\down");
            //pictures of paints to draw on canvas
            PaintPicker.pictures[0] = loadTexture2d("Pictures\\GenBall");
            PaintPicker.pictures[1] = loadTexture2d("Pictures\\platform");
            PaintPicker.pictures[2] = loadTexture2d("Pictures\\Edge");


            // sound settings-------------------
            
            music.SetVolume(5);
            DefaultAudioCategory.SetVolume(5);


            





            //sets screen draw ratio
            if (ScreenManager.ScreenWidth == 1440 && ScreenManager.ScreenHeight == 900)
            {
                
                ballScalar *= 0.75f;
                ballScalar *= GloabalStates.shrinkFactor;
                ConvertUnits.SetDisplayUnitToSimUnitRatio(22.5f);//the correct ratio,22.5 for 1440X900,
            }
            else if (ScreenManager.ScreenWidth == 1360 && ScreenManager.ScreenHeight == 768)
            {
                
                ballScalar *= 0.7f;
                ballScalar *= GloabalStates.shrinkFactor;
                ConvertUnits.SetDisplayUnitToSimUnitRatio(19.2f);
            }
            else if (ScreenManager.ScreenWidth == 1280 && ScreenManager.ScreenHeight == 800)
            {
                
                ballScalar *= 0.67f;
                ballScalar *= GloabalStates.shrinkFactor;
                ConvertUnits.SetDisplayUnitToSimUnitRatio(20f);
            }
            else if (ScreenManager.ScreenWidth == 1280 && ScreenManager.ScreenHeight == 768)
            {
                
                ballScalar *= 0.67f;
                ballScalar *= GloabalStates.shrinkFactor;
                ConvertUnits.SetDisplayUnitToSimUnitRatio(19.2f);
            }
            else if (ScreenManager.ScreenWidth == 1024 && ScreenManager.ScreenHeight == 768)
            {
                
                ballScalar *= 0.65f;
                ballScalar *= GloabalStates.shrinkFactor;
                ConvertUnits.SetDisplayUnitToSimUnitRatio(19.2f);
            }
            else if (ScreenManager.ScreenWidth == 800 && ScreenManager.ScreenHeight == 600)
            {
                
                ballScalar *= 0.52f;
                ballScalar *= GloabalStates.shrinkFactor;
                ConvertUnits.SetDisplayUnitToSimUnitRatio(15f);
            }
        }





















        //plays sound from xact sound bank
        public void playSound(int i)
        {
            if (i <= 7)
            {
                Cue Sound = null;


                if(i == 0)
                    Sound = soundBank.GetCue("theme");
                if (i == 1)
                    Sound = soundBank.GetCue("credits1");
                if (i == 2)
                    Sound = soundBank.GetCue("boing");
                if (i == 3)
                    Sound = soundBank.GetCue("fall");
                if (i == 4)
                    Sound = soundBank.GetCue("halo");
                if (i == 5)
                    Sound = soundBank.GetCue("hit");
                if (i == 6)
                    Sound = soundBank.GetCue("squeek");
                if (i == 7)
                    Sound = soundBank.GetCue("zip");

                music.SetVolume(5);
                DefaultAudioCategory.SetVolume(5);

                if(Sound.IsPrepared)
                    Sound.Play();
            }
        }




















        //draws line
        void drawLine(Vector2 a, Vector2 b, Color col)
        {
            //Texture2D spr = SpriteTextureLinePoint;

            Vector2 Origin = new Vector2(0.5f, 0.0f);
            Vector2 diff = b - a;
            float angle;
            Vector2 Scale = new Vector2(1.0f, diff.Length() / SpriteTextureLinePoint.Height);

            angle = (float)(Math.Atan2(diff.Y, diff.X)) - MathHelper.PiOver2;
            spriteBatch.Draw(SpriteTextureLinePoint, a, null, col, angle, Origin, Scale, SpriteEffects.None, 1.0f);
        }























        //draw menu for right click
        public void drawMenu()
        {
            if (GloabalStates.gameMenuState == GloabalStates.MenuState.MainMenu)//draws first menu for gameplay
            {

                if (gameMenuItemSelected == -1)//no item selected, all items will retract back into menu block
                {

                    for (int x = 0; x < 4; x++)
                        if ((SpriteMenuEntryOrigins[x].X - menuEntryOffsets[x]) < SpriteMenuEntryOrigins[x].X)
                            menuEntryOffsets[x] -= 8;

                }
                else//selected item only will extend toward edge of screen, all others will retract
                {
                    for (int x = 0; x < 4; x++)
                    {
                        if (gameMenuItemSelected == x && (SpriteMenuEntryOrigins[x].X - menuEntryOffsets[x] > 0))//item extending
                            menuEntryOffsets[x] += 8;
                        else if (gameMenuItemSelected != x && ((SpriteMenuEntryOrigins[x].X - menuEntryOffsets[x]) < SpriteMenuEntryOrigins[x].X))//other items retracting
                            menuEntryOffsets[x] -= 8;
                        
                    }
                }
                

                spriteBatch.Begin();
                spriteBatch.Draw(SpriteTextureGameMenu, SpriteGameMenuOrigin, Color.White);//game menu base

                for(int x=0;x<4;x++)//draw menu entry boxes
                    spriteBatch.Draw(SpriteTextureMenuEntry[x], new Vector2(SpriteMenuEntryOrigins[x].X - menuEntryOffsets[x], SpriteMenuEntryOrigins[x].Y), Color.White);

                if (GloabalStates.gameMenuState == GloabalStates.MenuState.MainMenu)//default
                    DrawMenuText(new String[]{"Pick Paint","Settings","Main Menu","Exit Game"});
                

                spriteBatch.End();
            }
            else if (GloabalStates.gameMenuState == GloabalStates.MenuState.PaintPicker)//draws paint picker menu system
            {
                spriteBatch.Begin();
                PaintPicker.drawPaintPickerMenu(spriteBatch, ScreenManager.ScreenWidth, ScreenManager.ScreenHeight, Font);
                spriteBatch.End();
            }
        }
















        /// <summary>
        /// Draws text to each menuEntry.
        /// </summary>
        public void DrawMenuText(String [] entries)
        {
            for (int x = 0; x < 4; x++)//draw menu entry boxes
                spriteBatch.DrawString(Font, entries[x], new Vector2((SpriteMenuEntryOrigins[x].X - menuEntryOffsets[x])+40, SpriteMenuEntryOrigins[x].Y+30), Color.White);
        }







































        /// <summary>
        /// checks user input from keyboard and mouse, called from within draw routine.
        /// </summary>
        public void InputTick()
        {
            KeyboardState ks = Keyboard.GetState();
            MouseState ms = Mouse.GetState();
            bool gameMenuActive = false;
            bool IntroMenu = false;

            //
            if (GloabalStates.gameMenuState == GloabalStates.MenuState.MainMenu)
                gameMenuActive = true;

            if (GloabalStates.currentGameState == GloabalStates.CurrentGameStateenum.Menu)
                IntroMenu = true;

            int y = ms.Y;
            int x = ms.X;
            int mSelected = -1;//current y dimension, menu selection

            SpritePaintBrushOrigin = new Vector2(x, y);//update mouse position




            //drawing objects for in game is here--------------------------------------------------------------------------------------
            if (!IntroMenu && GloabalStates.gameMenuState == GloabalStates.MenuState.GamePlay)
            {

                //level 1 win/loose actions here here
                if (GloabalStates.currentGameState == GloabalStates.CurrentGameStateenum.LevelOne)
                {
                    if (GloabalStates.levelStates == GloabalStates.LevelStates.Win || GloabalStates.levelStates == GloabalStates.LevelStates.Loose)
                    {
                        //restarts new game
                        if ((ms.LeftButton == ButtonState.Pressed) && (oldMS.LeftButton == ButtonState.Released) || (ms.RightButton == ButtonState.Pressed) && (oldMS.RightButton == ButtonState.Released))
                        {
                            //exit level 1 to main menu
                            lev1.ExitScreen();
                            GloabalStates.currentGameState = GloabalStates.CurrentGameStateenum.Menu;
                            GloabalStates.levelStates = GloabalStates.LevelStates.Play;
                            GloabalStates.edgeData.active = false;
                            GloabalStates.platformData.active = false;
                            GloabalStates.levelOneEdgesDrawn = false;


                            //new-up components and add to Game.Components
                            ScreenManager = new ScreenManager(this);
                            Components.Add(ScreenManager);

                            //FrameRateCounter frameRateCounter = new FrameRateCounter(ScreenManager);
                            //frameRateCounter.DrawOrder = 101;
                            //Components.Add(frameRateCounter);

                            lev1 = new LevelOne(this);
                            ScreenManager.MainMenuScreen.AddMainMenuItem(lev1.GetTitle(), lev1);
                            ScreenManager.MainMenuScreen.AddMainMenuItem("Exit", null, true);


                            ScreenManager.GoToMainMenu();

                            oldMS = ms;
                        }
                    }
                }



                //set up line drawing construct for platform and edge
                if ((ms.LeftButton == ButtonState.Pressed) && (oldMS.LeftButton == ButtonState.Released))
                {
                    if (GloabalStates.chosenPaint == GloabalStates.ChosenPaintenum.Platform)
                    {
                        GloabalStates.platformData.Origin = new Vector2(x,y);
                        GloabalStates.platformData.active = true;
                    }
                    else if (GloabalStates.chosenPaint == GloabalStates.ChosenPaintenum.Edge)
                    {
                        GloabalStates.edgeData.Origin = new Vector2(x,y);
                        GloabalStates.edgeData.active = true;
                    }
                }
                else if ((ms.LeftButton == ButtonState.Pressed) && (oldMS.LeftButton == ButtonState.Pressed))
                {
                    if (GloabalStates.chosenPaint == GloabalStates.ChosenPaintenum.Platform)
                    {
                        if (GloabalStates.platformData.Origin.X != x || GloabalStates.platformData.Origin.Y != y)
                        {
                            GloabalStates.platformData.EndPoint = new Vector2(x, y);
                        }
                    }
                    else if (GloabalStates.chosenPaint == GloabalStates.ChosenPaintenum.Edge)
                    {
                        if (GloabalStates.edgeData.Origin.X != x || GloabalStates.edgeData.Origin.Y != y)
                        {
                            GloabalStates.edgeData.EndPoint = new Vector2(x, y);
                        }
                    }
                }



                //left mouse release, creates objects
                if ((ms.LeftButton == ButtonState.Released) && (oldMS.LeftButton == ButtonState.Pressed))
                {
                        //draw ball on screen where mouse clicked
                        if (GloabalStates.chosenPaint == GloabalStates.ChosenPaintenum.Spere)
                        {
                            Vector2 position = ConvertUnits.ToSimUnits(new Vector2((x - screenW), -(y - screenH)));
                            lev1.CreateBall(position, 1 * GloabalStates.shrinkFactor);
                        }//draw platform
                        else if (GloabalStates.chosenPaint == GloabalStates.ChosenPaintenum.Platform)
                        {
                                        
                            Vector2 position = ConvertUnits.ToSimUnits(new Vector2(GloabalStates.platformData.Origin.X - screenW, -(GloabalStates.platformData.Origin.Y - screenH)));
                            Vector2 position2 = ConvertUnits.ToSimUnits(new Vector2(GloabalStates.platformData.EndPoint.X - screenW, -(GloabalStates.platformData.EndPoint.Y - screenH)));


                            lev1.CreatePlatform(position, new Vector2(Math.Abs(position2.X - position.X) * GloabalStates.shrinkFactor, Math.Abs(position2.Y - position.Y) * GloabalStates.shrinkFactor));
                            GloabalStates.platformData.active = false;
                        }
                        else if (GloabalStates.chosenPaint == GloabalStates.ChosenPaintenum.Edge)
                        {
                            Vector2 position = ConvertUnits.ToSimUnits(new Vector2(GloabalStates.edgeData.Origin.X - screenW, -(GloabalStates.edgeData.Origin.Y - screenH)));
                            Vector2 position2 = ConvertUnits.ToSimUnits(new Vector2(GloabalStates.edgeData.EndPoint.X - screenW, -(GloabalStates.edgeData.EndPoint.Y - screenH)));

                            lev1.CreateEdge(position,position2);
                            GloabalStates.edgeData.active = false;
                        }
                }
                    
                    
            }



            //check mouse coords for main menu only------------------------------------------------------------------------------
            if (gameMenuActive)
            {
                //check y mouse coordinates
                for (int c = 0; c < 4; c++)
                {
                    if (y > SpriteMenuEntryOrigins[c].Y)
                    {
                        if (c != 3 && y < SpriteMenuEntryOrigins[c + 1].Y)
                        {
                            //menu item c is selected
                            mSelected = c;
                        }
                        else if (y < SpriteMenuEntryOrigins[c].Y + 70)
                        {
                            //menu item 3 is selected
                            mSelected = c;
                        }
                    }
                }

                //check x mouse coord
                if (x < ScreenManager.ScreenWidth / 3)
                {
                    if (mSelected != -1)
                    {
                        gameMenuItemSelected = mSelected;
                    }
                    else
                    {
                        gameMenuItemSelected = -1;
                    }
                }
                else
                {
                    gameMenuItemSelected = -1;
                }

                //check for left mouse click
                if ((ms.LeftButton == ButtonState.Pressed) && (oldMS.LeftButton == ButtonState.Released))
                {
                    
                    if (gameMenuItemSelected == 0)//paint picker menu
                    {
                        GloabalStates.gameMenuState = GloabalStates.MenuState.PaintPicker;
                        playSound(5);
                    }
                    else if (gameMenuItemSelected == 1)
                    {
                        playSound(5);
                    }
                    else if (gameMenuItemSelected == 2)
                    {
                        playSound(5);
                    }
                    else if (gameMenuItemSelected == 3)//exits game
                        this.Exit();

                }

            }//------------------------PaintPicker---------------------------------------------------------------------------------
            else if (GloabalStates.gameMenuState == GloabalStates.MenuState.PaintPicker)//input for paint picker menu
            {
                if (x > PaintPicker.upPoint.X && x < PaintPicker.upPoint.X + 50 && y > PaintPicker.upPoint.Y && y < PaintPicker.upPoint.Y + 50)
                {
                    
                    //up button
                    if ((ms.LeftButton == ButtonState.Pressed) && (oldMS.LeftButton == ButtonState.Released))
                    {
                        PaintPicker.incrementPic();
                        //up button mouse hover
                        playSound(6);
                    }
                }
                else if (x > PaintPicker.downPoint.X && x < PaintPicker.downPoint.X + 50 && y > PaintPicker.downPoint.Y && y < PaintPicker.downPoint.Y + 50)
                {
                    
                    //down button
                    if ((ms.LeftButton == ButtonState.Pressed) && (oldMS.LeftButton == ButtonState.Released))
                    {
                        PaintPicker.decrementPic();
                        //down button mouse hover
                        playSound(6);
                    }
                }
            }

            


            


            //pauses game and bring up game menu bar
            if ((ms.RightButton == ButtonState.Pressed) && (oldMS.RightButton == ButtonState.Released) && !gameMenuActive && !IntroMenu)
            {
                GraphicsDevice.ResolveBackBuffer(renderTargetTexture);
                GloabalStates.gameMenuState = GloabalStates.MenuState.MainMenu;
                lev1.pauseLevel();
                
            }
            //goes back to game from pause
            else if ((ms.RightButton == ButtonState.Pressed) && (oldMS.RightButton == ButtonState.Released) && gameMenuActive && !IntroMenu)
            {
                GloabalStates.gameMenuState = GloabalStates.MenuState.GamePlay;
                lev1.unPauseLevel();
            }

            //if escape button is pressed
            if (ks.IsKeyDown(Keys.Escape) && oldKS.IsKeyUp(Keys.Escape))
            {
                this.Exit();
            }

            //game lost
            if (GloabalStates.levelStates == GloabalStates.LevelStates.Loose && !lev1.isPaused)
            {
                lev1.pauseLevel();
            }
            else if (GloabalStates.levelStates == GloabalStates.LevelStates.Win && !lev1.isPaused)
            {
                lev1.pauseLevel();
            }

            //new states placed in old states.
            oldKS = ks;
            oldMS = ms;
        }




        


































        /// <summary>
        /// This is called when the game should draw itself.
        /// </summary>
        /// <param name="gameTime">Provides a snapshot of timing values.</param>
        protected override void Draw(GameTime gameTime)
        {
            ScreenManager.GraphicsDevice.Clear(Color.Black);

            if (!(GloabalStates.gameMenuState == GloabalStates.MenuState.MainMenu))//no game menu-------------------------------------------
            {
                spriteBatch.Begin();//sprite batch start----------------------------------------------------------
                if (lev1.IsExiting)
                {
                    lev1.isPlaying = false;
                }

                

                if (GloabalStates.currentGameState == GloabalStates.CurrentGameStateenum.Menu)
                {
                    //draw video here--------------
                    //movie.Draw(gameTime, spriteBatch);
                    

                    //draw game title
                    spriteBatch.DrawString(Font2, "A Game Called Painting", GameTitleOrigin, Color.White);
                    
                }
                else if(movie.isPlaying())
                {
                    movie.stop();
                }

                
               
                //draw background---------------------------SpriteTextureBackGround1
                if (GloabalStates.currentGameState == GloabalStates.CurrentGameStateenum.LevelOne)//level one logic
                {
                    spriteBatch.Draw(SpriteTextureBackGround1, new Rectangle(0, 0, ScreenManager.ScreenWidth, ScreenManager.ScreenHeight), Color.White);
                }
                //------------------------------------------
                spriteBatch.End();//sprite batch end----------------------------------------------------------

                ScreenManager.Draw(gameTime);//draw farseer debug view





                




                spriteBatch.Begin();//sprite batch begin----------------------------------------------
                if (GloabalStates.currentGameState == GloabalStates.CurrentGameStateenum.LevelOne)//level one paint logic-------------------------
                {
                    if (!GloabalStates.levelOneEdgesDrawn)
                    {
                        Vector2 Position = ConvertUnits.ToSimUnits(new Vector2((barrelPosLev1.X + (35 * GloabalStates.shrinkFactor)) - screenW, -((barrelPosLev1.Y + (65 * GloabalStates.shrinkFactor)) - screenH)));
                        Vector2 Position2 = ConvertUnits.ToSimUnits(new Vector2((barrelPosLev1.X + (35 * GloabalStates.shrinkFactor)) - screenW, -((barrelPosLev1.Y + (140 * GloabalStates.shrinkFactor)) - screenH)));
                        lev1.CreateEdge(Position, Position2);

                        Position = ConvertUnits.ToSimUnits(new Vector2((barrelPosLev1.X + (125 * GloabalStates.shrinkFactor)) - screenW, -((barrelPosLev1.Y + (65 * GloabalStates.shrinkFactor)) - screenH)));
                        Position2 = ConvertUnits.ToSimUnits(new Vector2((barrelPosLev1.X + (125 * GloabalStates.shrinkFactor)) - screenW, -((barrelPosLev1.Y + (140 * GloabalStates.shrinkFactor)) - screenH)));
                        lev1.CreateEdge(Position, Position2);

                        
                        GloabalStates.levelOneEdgesDrawn = true;
                    }
                    
                    lev1.updateBall();//upates screen ratio
                    Vector2 position = ConvertUnits.ToDisplayUnits(lev1.BallPostion);
                    Vector2 newPos = new Vector2((position.X + screenW), ((-position.Y) + screenH));

                    //win condition, if ball is in barrel
                    if (barrelPosLev1.X + (25 * GloabalStates.shrinkFactor) < newPos.X && newPos.X < barrelPosLev1.X + (130 * GloabalStates.shrinkFactor))
                        if (barrelPosLev1.Y + (70 * GloabalStates.shrinkFactor) < newPos.Y && newPos.Y < barrelPosLev1.Y + (100 * GloabalStates.shrinkFactor))
                        {
                            GloabalStates.levelStates = GloabalStates.LevelStates.Win;
                        }


                    //if ball is bellow threshold then player looses
                    if (newPos.Y > ScreenManager.ScreenHeight * 2)
                        GloabalStates.levelStates = GloabalStates.LevelStates.Loose;

                    
                    //SpriteTextureBarrelBacking
                    spriteBatch.Draw(SpriteTextureBarrelBacking, new Rectangle((int)barrelPosLev1.X, (int)barrelPosLev1.Y, (int)(SpriteTextureBarrelBacking.Width * GloabalStates.shrinkFactor), (int)(SpriteTextureBarrelBacking.Height * GloabalStates.shrinkFactor)), Color.White);
                    //texture ball
                    spriteBatch.Draw(SpriteTextureBall, (Vector2)newPos, null, Color.White, lev1.BallRotation, SpriteTextureBallOrigin, ballScalar, SpriteEffects.None, 0f);
                    //SpriteTextureBarrel
                    spriteBatch.Draw(SpriteTextureBarrel, new Rectangle((int)barrelPosLev1.X, (int)barrelPosLev1.Y, (int)(SpriteTextureBarrel.Width * GloabalStates.shrinkFactor), (int)(SpriteTextureBarrel.Height * GloabalStates.shrinkFactor)), Color.White);
                    
                }
                else if (GloabalStates.currentGameState == GloabalStates.CurrentGameStateenum.LevelTwo)//level's two paint logic
                {

                }
                else//Intro menu
                {

                }

                spriteBatch.End();//sprite batch end----------------------------------------------------
            }
            else//game menu - pause logic-------------------------------------------------
            {
                //draws screen capture for pause effect
                spriteBatch.Begin();//sprite batch begin----------------------------------------------
                spriteBatch.Draw(renderTargetTexture, Vector2.Zero, Color.White);
                spriteBatch.End();//sprite batch end----------------------------------------------------
            }
            

            InputTick();//checks user input for drawing
            drawMenu();//draws hud menu last


            spriteBatch.Begin();//sprite batch begin----------------------------------------------
            //if intro menu not running
            if (GloabalStates.currentGameState != GloabalStates.CurrentGameStateenum.Menu)//draw cursor
            {
                //draws loose texture
                if (GloabalStates.levelStates == GloabalStates.LevelStates.Loose)
                {
                    
                    spriteBatch.Draw(SpriteTextureLoose, new Rectangle(0, 0, ScreenManager.ScreenWidth, ScreenManager.ScreenHeight), Color.White);
                    
                }
                else if (GloabalStates.levelStates == GloabalStates.LevelStates.Win)
                {
                    spriteBatch.Draw(SpriteTextureWin, new Rectangle(0, 0, ScreenManager.ScreenWidth, ScreenManager.ScreenHeight), Color.White);
                }

                //draw paint brush at the very end
                if (GloabalStates.platformData.active)
                {
                    drawLine(new Vector2(GloabalStates.platformData.Origin.X, GloabalStates.platformData.Origin.Y), new Vector2(GloabalStates.platformData.EndPoint.X, GloabalStates.platformData.Origin.Y), Color.Black);
                    drawLine(new Vector2(GloabalStates.platformData.Origin.X, GloabalStates.platformData.Origin.Y), new Vector2(GloabalStates.platformData.Origin.X, GloabalStates.platformData.EndPoint.Y), Color.Black);
                    drawLine(new Vector2(GloabalStates.platformData.EndPoint.X, GloabalStates.platformData.EndPoint.Y), new Vector2(GloabalStates.platformData.EndPoint.X, GloabalStates.platformData.Origin.Y), Color.Black);
                    drawLine(new Vector2(GloabalStates.platformData.EndPoint.X, GloabalStates.platformData.EndPoint.Y), new Vector2(GloabalStates.platformData.Origin.X, GloabalStates.platformData.EndPoint.Y), Color.Black);
                }
                else if (GloabalStates.edgeData.active)
                {
                    drawLine(new Vector2(GloabalStates.edgeData.Origin.X, GloabalStates.edgeData.Origin.Y), new Vector2(GloabalStates.edgeData.EndPoint.X, GloabalStates.edgeData.EndPoint.Y), Color.Black);
                }
                spriteBatch.Draw(SpriteTexturePaintBrush, SpritePaintBrushOrigin, Color.White);
            }



            

            //monitor performance
            if (GloabalStates.performanceData.MonitorPerformance)
            {
                //updates fps
                frameRateCounter.Update(gameTime);

                //updates performance data every second
                if (gameTime.TotalGameTime.Milliseconds % 1000d < 0.0001)
                {
                    GloabalStates.performanceData.cpu = getCurrentCpuUsage();
                    GloabalStates.performanceData.mem = getAvailableRAM();
                }

                spriteBatch.DrawString(Font, "CPU=" + GloabalStates.performanceData.cpu + " \nMEM=" + GloabalStates.performanceData.mem + "\nslow?" + gameTime.IsRunningSlowly + "\nFPS=" + frameRateCounter._frameRate, Vector2.Zero, Color.Red);
            }


            spriteBatch.End();//sprite batch end----------------------------------------------------

            //base will be cancled so we can create a custom draw routine
            //base.Draw(gameTime);
        }


























        //windows size changes
        private void Window_ClientSizeChanged(object sender, EventArgs e)
        {
            if (Window.ClientBounds.Width > 0 && Window.ClientBounds.Height > 0)
            {
                _graphics.PreferredBackBufferWidth = Window.ClientBounds.Width;
                _graphics.PreferredBackBufferHeight = Window.ClientBounds.Height;

            }
            

        }
    }
}